﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SystemFrameWork;

namespace DutyWeb.UserControls
{
    public partial class UploadFile : BaseUserControl
    {
        /// <summary>
        /// 
        /// </summary>
        public FileUpload CurrentUpload
        {
            get
            {
                return this.fileUpload;
            }
        }

        public bool IsDelete
        {
            get
            {
                return (bool)ViewState["IsDelete"];
            }

            set
            {
                ViewState["IsDelete"] = value;
            }
        }

        /// <summary>
        /// the file format collection
        /// </summary>
        public string FileFormat
        {
            get
            {
                return ConfigurationHelper.FileFormat;
            }
        }

        /// <summary>
        /// true: the user will be able to view the file
        /// false:the user won't be able to view the file
        /// </summary>
        public bool EnableViewFile
        {
            get;
            set;
        }

        /// <summary>
        /// 
        /// </summary>
        public byte[] FileBinary
        {
            get
            {
                return FileHelper.GetFileBinary(this.LabFileName.Text);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public string FileName
        {
            get
            {
                return this.litFileName.Text;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public string DeletedFileName
        {
            get
            {
                return LabDeletedFileName.Text;
            }
        }

        /// <summary>
        /// the event will be triggered when file format is not correct
        /// </summary>
        public event EventHandler ShowErrorEvent;

        /// <summary>
        /// 
        /// </summary>
        public event EventHandler ClearTheDbDirtyData;

        /// <summary>
        /// 
        /// </summary>
        public event EventHandler SupperAddUrl2DB;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                this.btnDelete.Attributes.Add("onclick", string.Format("return myConfirm('{0}')", "您确实要删除吗？"));
                this.btnUpload.Attributes.Add("onclick", "return CheckFileSize('" + ConfigurationHelper.FolderSizeLimit + "','fileUpload','" + string.Format("上传文件大小不能大于{0}兆", this.FolderSizeLimitToMB) + "');");
                this.lblViewGraphic.Visible = this.EnableViewFile;
                this.IsDelete = false;
            }
        }

        /// <summary>
        /// not really load the file,
        /// only display the file name
        /// </summary>
        public void LoadFile(string fileName)
        {
            this.litFileName.Text = fileName;
            if (!string.IsNullOrEmpty(fileName))
            {
                this.panDelete.Visible = true;
                this.panUpload.Visible = false;

                string filePath = string.Format("{0}/{1}/{2}", base.GetBaseUrl(), base.FileUploadRelativePath, fileName);
                //UserSession.CurrentSession.TempFileUrl = this.LabFileName.Text;
                this.lblViewGraphic.Attributes.Add("onclick", string.Format("return WindowOpen(\"../files/GraphicGenerator.aspx?picType=3&path={0}\");", Server.UrlEncode(filePath)));

            }
            else
            {
                this.panDelete.Visible = false;
                this.panUpload.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public bool Upload()
        {
            if (string.IsNullOrEmpty(this.fileUpload.FileName))
            {
                string msg = string.Format("{0}", "文件格式错误");
                ShowErrorEvent(msg, null);
                return false;
            }

            if (!FileHelper.IsAllowableFileType(this.fileUpload.FileName, this.FileFormat))
            {
                string msg = string.Format("{0}", "文件格式错误");
                ShowErrorEvent(msg, null);
                return false;
            }

            string extension = Path.GetExtension(this.fileUpload.FileName);
            //check the file format

            Guid mid = Guid.NewGuid();
            this.LabFileName.Text = string.Format("{0}\\{1}{2}", base.FileUplodePath, mid, extension);
            string filePath = string.Format("{0}/{1}/{2}{3}", base.GetBaseUrl(), base.FileUploadRelativePath, mid, extension);
            this.fileUpload.SaveAs(this.LabFileName.Text);
            this.litFileName.Text = string.Format("{0}{1}", mid, extension);

            //UserSession.CurrentSession.TempFileUrl = this.LabFileName.Text;
            this.lblViewGraphic.Attributes.Add("onclick", string.Format("return WindowOpen(\"../files/GraphicGenerator.aspx?picType=3&path={0}\");", Server.UrlEncode(filePath)));
            this.SupperAddUrl2DB(null, null);
            return true;
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            bool bl = Upload();
            if (bl)
            {
                this.panDelete.Visible = true;
                this.panUpload.Visible = false;
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            DeleteTheTempFile();
            this.panDelete.Visible = false;
            this.panUpload.Visible = true;
            this.IsDelete = true;
        }

        public void DeleteTheTempFile()
        {
            this.LabFileName.Text = string.Format("{0}\\{1}", base.FileUplodePath, this.FileName);
            FileHelper.DeleteTempFile(this.LabFileName.Text);
            this.LabDeletedFileName.Text = this.litFileName.Text;
            this.litFileName.Text = "";
            this.ClearTheDbDirtyData(null, null);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="picType"></param>
        public void Prepare2ViewGraphic(string id, string picType)
        {
            this.lblViewGraphic.Attributes.Add("onclick", string.Format("return WindowOpen(\"../files/GraphicGenerator.aspx?picType={0}&id={1}\");", picType, id));
        }

        /// <summary>
        /// File Limit
        /// </summary>
        private string FolderSizeLimitToMB
        {
            get
            {
                float limit = float.Parse(ConfigurationHelper.FolderSizeLimit) / (1024 * 1024);
                return limit.ToString("0.00");
            }
        }
    }
}